<template>
  <div>
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="注册"
      fixed
      placeholder 
      @click-left="$router.back()"
      class="top-nav-bar"
    >
      <!-- 左侧文本 -->
      <template #left>
        <div class="top-nav-bar-left-arrow">
          <van-icon name="arrow-left" color="#ee0a24"/>
        </div>
      </template>
    </van-nav-bar>
    <!-- 美多商城logo -->
    <MeiduoLogo></MeiduoLogo>
    <!-- 输入框 -->
    <van-cell-group :border="false" class="ipt-box">
      <!-- 手机号码 -->
      <van-field
        v-model="userTelephone"
        label="手机号码"
        type="tel"
        left-icon="phone-o"
        placeholder="请输入手机号码"
        center
        :maxlength="userConstants.USER_TELEPHONE_LENGTH"
        class="ipt"
        ref="userTelephone"
        @focus="iptFocus('userTelephone')"
        @blur="iptBlur('userTelephone')"
      >
        <template #right-icon>
          <!-- 输入格式是否正确的图标与清除输入的图标不能同时显示 -->
          <van-icon name="success" color="green" v-show="isUserTelephoneOk && !isUserTelephoneClearShow"/>
          <van-icon name="cross" color="red" v-show="!isUserTelephoneOk && !isUserTelephoneClearShow"/>
          <van-icon name="close" v-show="isUserTelephoneClearShow" @click="clearInput('userTelephone')"/>
        </template>
      </van-field>
      <!-- 密码 -->
      <van-field
        v-model="userPassword"
        label="密码"
        :type="isPasswordEyeOpen ? 'text' : 'password'"
        left-icon="edit"
        placeholder="请输入密码"
        center
        :maxlength="userConstants.USER_PASSWORD_MAX_LENGTH"
        class="ipt"
        ref="userPassword"
        @focus="iptFocus('userPassword')"
        @blur="iptBlur('userPassword')"
      >
        <template #right-icon>
          <!-- 输入格式是否正确的图标与清除输入的图标不能同时显示 -->
          <van-icon name="success" color="green" v-show="isUserPasswordOk && !isUserPasswordClearShow"/>
          <van-icon name="cross" color="red" v-show="!isUserPasswordOk && !isUserPasswordClearShow"/>
          <div class="ipt-pwd-right-icon">
            <van-icon 
              name="closed-eye" 
              class="icon icon-eye" 
              v-show="isUserPasswordClearShow && !isPasswordEyeOpen"
              @click="changeEye('userPassword')"
            />
            <van-icon 
              name="eye-o" 
              class="icon icon-eye" 
              v-show="isUserPasswordClearShow && isPasswordEyeOpen"
              @click="changeEye('userPassword')"
            />
            <van-icon 
              name="close" 
              class="icon" 
              v-show="isUserPasswordClearShow" 
              @click="clearInput('userPassword')"
            />
          </div>
        </template>
      </van-field>
      <!-- 确认密吗 -->
      <van-field
        v-model="userPasswordConfim"
        label="确认密码"
        :type="isPasswordConfigEyeOpen ? 'text' : 'password'"
        left-icon="edit"
        placeholder="请再次输入密码"
        center
        :maxlength="userConstants.USER_PASSWORD_MAX_LENGTH"
        class="ipt"
        ref="userPasswordConfim"
        @focus="iptFocus('userPasswordConfim')"
        @blur="iptBlur('userPasswordConfim')"
      >
        <template #right-icon>
          <!-- 输入格式是否正确的图标与清除输入的图标不能同时显示 -->
          <van-icon name="success" color="green" v-show="isUserPasswordConfigOk && !isUserPasswordConfimClearShow"/>
          <van-icon name="cross" color="red" v-show="!isUserPasswordConfigOk && !isUserPasswordConfimClearShow"/>
          <div class="ipt-pwd-right-icon">
            <van-icon 
              name="closed-eye" 
              class="icon icon-eye" 
              v-show="isUserPasswordConfimClearShow && !isPasswordConfigEyeOpen"
              @click="changeEye('userPasswordConfim')"
            />
            <van-icon 
              name="eye-o" 
              class="icon icon-eye" 
              v-show="isUserPasswordConfimClearShow && isPasswordConfigEyeOpen"
              @click="changeEye('userPasswordConfim')"
            />
            <van-icon 
              name="close" 
              class="icon" 
              v-show="isUserPasswordConfimClearShow" 
              @click="clearInput('userPasswordConfim')"
            />
          </div>
        </template>
      </van-field>
      <!-- 短信验证码 -->
      <van-field
        v-model="smsVerificationCode"
        label="短信验证码"
        type="number"
        left-icon="envelop-o"
        placeholder="请输入短信验证码"
        center
        :maxlength="userConstants.SMS_VERIFICATION_CODE_LENGTH"
        class="ipt"
        ref="smsVerificationCode"
        @focus="iptFocus('smsVerificationCode')"
        @blur="iptBlur('smsVerificationCode')"
      >
        <template #right-icon>
          <!-- 输入格式是否正确的图标与清除输入的图标不能同时显示 -->
          <van-icon name="close" v-show="isSmsVerificationCodeClearShow" @click="clearInput('smsVerificationCode')"/>
        </template>
        <template #button>
          <van-button 
            size="small" 
            color="#ee0a24" 
            class="sms-code-btn" 
            @click="sendSmsVerificationCode"
            :disabled="!isSend"
          >
            {{isSend ? '发送验证码' : smsVerificationCodeSendAgainWaitTime+'s'}}
          </van-button>
        </template>
      </van-field>
    </van-cell-group>
    <!-- 注册按钮 -->
    <van-button 
      color="linear-gradient(to right, #ff6034, #ee0a24)" 
      class="ipt"
      @click="register"
    >立即注册</van-button>
  </div>
</template>

<script>
import MeiduoLogo from '@/components/MeiduoLogo.vue'
import { CellGroup  } from 'vant'
import { Field } from 'vant' // 输入框

export default {
  name: 'Register',
  components: {
    MeiduoLogo,
    [CellGroup.name]: CellGroup,
    [Field.name]: Field,
  },
  data() {
    return {
      userTelephone: '', // 用户手机号
      isUserTelephoneClearShow: false, // 输入手机号清除按钮是否显示
      isUserTelephoneOk: false, // 用户输入的手机号格式是否正确

      userPassword: '', // 用户账号密码
      isUserPasswordClearShow: false, // 输入密码清除按钮是否显示
      isPasswordEyeOpen: false, // 输入密码的输入框眼睛是否打开，如果眼睛打开则密码可视 
      isUserPasswordOk: false, // 用户输入的密码格式是否正确
      
      userPasswordConfim: '', // 用户确认账号密码
      isUserPasswordConfimClearShow: false, // 输入确认密吗清除按钮是否显示
      isPasswordConfigEyeOpen: false, // 输入确认密码的输入框眼睛是否打开，如果眼睛打开则密码可视
      isUserPasswordConfigOk: false, // 用户确认密码是否正确
      
      smsVerificationCode: '', // 短信验证码
      isSmsVerificationCodeClearShow: false, // 输入短信验证码清除按钮是否显示
      smsVerificationCodeSendAgainWaitTime: 0, // 再次发送短信验证码所需等待的时间
      isSend: true, // 是否可以发送短信验证码
    }
  },
  methods: {
    // 输入框获取焦点，显示清除输入按钮
    iptFocus(iptName) {
      setTimeout(()=>{ // 让显示按钮进入异步队列，页面更新之后显示按钮
        switch (iptName) {
          case 'userTelephone':
            this.isUserTelephoneClearShow = true
            break
          case 'userPassword':
            this.isUserPasswordClearShow = true
            break
          case 'userPasswordConfim':
            this.isUserPasswordConfimClearShow = true
            break
          case 'smsVerificationCode':
            this.isSmsVerificationCodeClearShow = true
            this.isPasswordEyeOpen = false // 将密码修改为不可视
            this.isPasswordConfigEyeOpen = false // 将确认密码修改为不可视
            break
          default:
            break
        }
      }, 0)
    },
    // 输入框失去焦点，隐藏清除输入按钮
    iptBlur(iptName) {
      setTimeout(()=>{ // 让异常清除按钮进入异步队列，先清除文本框再隐藏清除按钮
        switch (iptName) {
          case 'userTelephone':
            this.isUserTelephoneClearShow = false
            // 校验手机号
            if (this.userTelephone.length === 0) { // 没有输入手机号码仅显示错误图标
              this.isUserTelephoneOk = false
            } else { // 输入手机号码格式不正确显示错误图标外加提示
              this.isUserTelephoneOk = this.userConstants.USER_TELEPHONE_REGULAR.test(this.userTelephone)
              if (!this.isUserTelephoneOk) {
                this.$toast.fail('您输入的手机号码格式不正确')
              }
            }
            break
          case 'userPassword':
            this.isUserPasswordClearShow = false
            // 校验密码
            // 当前对于密码只进行长度的校验
            if (this.userPassword.length === 0) {
              this.isUserPasswordOk = false
            } else {
              this.isUserPasswordOk = (this.userPassword.length >= this.userConstants.USER_PASSWORD_MIN_LENGTH ? true : false)
              if (!this.isUserPasswordOk) {
                this.$toast.fail('您输入的密码长度不足 '+this.userConstants.USER_PASSWORD_MIN_LENGTH+' 位')
              }
            }
            break
          case 'userPasswordConfim':
            this.isUserPasswordConfimClearShow = false
            // 校验密码的确认
            if (this.userPasswordConfim.length === 0) {
              this.isUserPasswordConfigOk = false
              if (this.userPassword.length > 0) {
                this.$toast.fail('请再次输入密码')
              }
            } else {
              this.isUserPasswordConfigOk = (this.userPassword === this.userPasswordConfim) ? true : false
              if (!this.isUserPasswordConfigOk) {
                this.$toast.fail('确认密码输入有误')
              }
            }
            break
          case 'smsVerificationCode':
            this.isSmsVerificationCodeClearShow = false
            break
          default:
            break
        }
      })
    },
    // 清除输入
    clearInput(iptName) {
      switch (iptName) { // 清除对应的输入框的文本
        case 'userTelephone':
          this.userTelephone = ''
          break
        case 'userPassword':
          this.userPassword = ''
          break
        case 'userPasswordConfim':
          this.userPasswordConfim = ''
          break
        case 'smsVerificationCode':
          this.smsVerificationCode = ''
          break
        default:
          break
      }
      this.$nextTick(()=>{ // 等待页面更新后当前输入框再次获取焦点
        this.$refs[iptName].focus()
      })
    },
    // 改变眼睛样式，改变密码是否可视
    changeEye(iptName) {
      switch (iptName) {
        case 'userPassword':
          this.isPasswordEyeOpen = !this.isPasswordEyeOpen
          break;
        case 'userPasswordConfim':
          this.isPasswordConfigEyeOpen = !this.isPasswordConfigEyeOpen
          break;
        default:
          break;
      }
      this.$nextTick(()=>{ // 等待页面更新后当前输入框再次获取焦点
        this.$refs[iptName].focus()
      })
    },
    // 发送短信验证码
    sendSmsVerificationCode() {
      this.isPasswordEyeOpen = false // 将密码修改为不可视
      this.isPasswordConfigEyeOpen = false // 将确认密码修改为不可视
      // 判断前面的输入是否格式正确
      if (!this.isUserTelephoneOk) { // 手机号码输入格式错误
        this.$toast.fail('您输入的手机号码格式不正确')
        return
      }
      if (!this.isUserPasswordOk) { // 密码格式错误
        this.$toast.fail('您输入的密码格式不正确')
        return
      }
      if (!this.isUserPasswordConfigOk) { // 确认密码输入错误
        this.$toast.fail('确认密码错误')
        return
      }
      // 发送短信验证码
      this.$toast.loading({message: '发送短信验证码...', forbidClick: true}) // 加载轻提示，禁止点击
      this.req.get(
        'user/register/',
        {
          params: {
            userTelephone: this.userTelephone
          }
        }
      ).then(res=>{
        this.$toast.clear()
        if (res.data.mark === 1) {
          this.$toast.success(res.data.message)
        } else {
          this.$toast.fail(res.data.message)
        }
      }, err=>{
        this.$toast.fail(err)
      })
      this.isSend = false // 点击之后修改不可发送短信验证码
      this.interval = setInterval(()=>{ // 开启定时器
        // console.log(this.smsVerificationCodeSendAgainWaitTime)
        this.smsVerificationCodeSendAgainWaitTime -= 1 
      }, 1000) 

    },
    // 注册
    register() {
      if (!this.isUserTelephoneOk) { // 手机号码输入格式错误
        this.$toast.fail('您输入的手机号码格式不正确')
        return
      }
      if (!this.isUserPasswordOk) { // 密码格式错误
        this.$toast.fail('您输入的密码格式不正确')
        return
      }
      if (!this.isUserPasswordConfigOk) { // 确认密码输入错误
        this.$toast.fail('确认密码错误')
        return
      }
      if (this.smsVerificationCode.length !== this.userConstants.SMS_VERIFICATION_CODE_LENGTH) {  // 短信验证码格式错误
        this.$toast.fail('短信验证码为 ' + this.userConstants.SMS_VERIFICATION_CODE_LENGTH + ' 位数字')
        return
      }
      this.$toast.loading({message: '账号注册中...', forbidClick: true})
      this.req.post(
        'user/register/', 
        {
          userTelephone: this.userTelephone,
          userPassword: this.userPassword,
          smsVerificationCode: this.smsVerificationCode
        }
      ).then(res=>{
        // console.log(res)
        this.$toast.clear()
        if (res.data.mark === 1) { // 注册成功
          this.$toast.success(res.data.message)
          this.$router.replace({name: 'login'}) // 跳转到登陆页面
        } else { // 注册失败
          this.$toast.fail(res.data.message)
        }
      }, err=>{ // 请求失败
        // console.log(err)
        this.$toast.fail(err)
      })
    }
  },
  watch: {
    // 监视可以再次发送短信验证码所需等待的时间
    smsVerificationCodeSendAgainWaitTime(newVal) {
      if(newVal === 0) { // 等待时间结束
        this.isSend = true  // 可以再次发送短信验证码
        clearInterval(this.interval) // 清除定时器
        this.smsVerificationCodeSendAgainWaitTime = this.userConstants.SMS_VERIFICATION_CODE_SEND_AGAIN_WAIT_TIME // 重置等待时间
      }
    }
  },
  created() {
    this.smsVerificationCodeSendAgainWaitTime = this.userConstants.SMS_VERIFICATION_CODE_SEND_AGAIN_WAIT_TIME // 获取再次发送短信验证码所需等待的时间
  },
  beforeDestroy() {
    clearInterval(this.interval) // 清除定时器，防止定时器还存在时组件销毁
  }
}
</script>

<style lang="less" scoped>
// 输入框盒子样式
.ipt-box {
  margin: 10% 0 0;
}
// input样式
.ipt {
  margin: 5% 5%;
  height: 3.5rem;
  width: 90%;
  border: 1px solid #ee0a24;
  border-radius: 1.75rem;
}
// 密码输入框右侧图标样式 
.ipt-pwd-right-icon {
  width: 4rem;
  .icon {
    display: inline-block;
  }
  .icon-eye {
    margin: 0 20% 0 0;
    line-height: 100%;
    vertical-align: middle; // 设置对齐的基准线，图标垂直居中对齐
    font-size: 1.4rem;
  }
}
// 发送短信验证码按钮样式
.sms-code-btn {
  height: 2rem;
  width: 7rem;
  border-radius: 1rem;
}
</style>